import printTemplateService from "@/api/services/tool/printTemplateService";
import autoCodeRuleService from "@/api/services/tool/ruleService";
import SingleMaterialSelector from "@/pages/components/selector/SingleMaterialSelect";
import {
  ExportOutlined,
  PrinterOutlined,
  ReloadOutlined,
} from "@ant-design/icons";
import {
  Button,
  Col,
  Form,
  Input,
  InputNumber,
  Row,
  Select,
  Spin,
  Table,
  Tabs,
  message,
} from "antd";
import { useEffect, useState } from "react";
import { styled } from "styled-components";
import type { AutoCodeRule } from "../autoRule/entity";
import type { ToolLabelRecord } from "../labelRecord/entity";
import type { PrintRequest, PrintTemplate } from "./entity";

const StyledForm = styled(Form)`
  .ant-form-item-label > label {
    font-size: 16px !important;
    font-weight: bold;
  }
`;

const LabelPrint = () => {
  // 表单引用
  const [form] = Form.useForm();

  // 状态管理
  const [codeRuleList, setCodeRuleList] = useState<AutoCodeRule[]>([]);
  const [templateList, setTemplateList] = useState<PrintTemplate[]>([]);
  const [printRecordList, setPrintRecordList] = useState<ToolLabelRecord[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [selectMaterialVisiable, setSelectMaterialVisiable] = useState(false);

  // 加载保存的表单数据
  useEffect(() => {
    const savedData = localStorage.getItem("labelPrintFormData");
    if (savedData) {
      const parsedData = JSON.parse(savedData);
      form.setFieldsValue(parsedData);
    }
  }, [form]);

  // 保存表单数据到localStorage
  const saveFormData = (values: PrintRequest) => {
    localStorage.setItem("nameplatePrintFormData", JSON.stringify(values));
  };

  // 监听表单值变化，保存数据
  useEffect(() => {
    const values = form.getFieldsValue();
    if (Object.keys(values).length > 0) {
      saveFormData(values);
    }
  }, [form.getFieldsValue()]);

  // 组件卸载前保存数据
  useEffect(() => {
    // 获取编码规则
    autoCodeRuleService.selectList().then((res) => {
      if (res && res.length > 0) {
        setCodeRuleList(res);
      } else {
        message.error("该物料没有维护编码规则，请添加编码规则。");
      }
    });

    // 获取打印模板
    printTemplateService.selectList().then((res) => {
      if (res && res.length > 0) {
        setTemplateList(res);
      } else {
        message.error("该物料没有维护打印模板，请添加打印模板。");
      }
    });

    return () => {
      const values = form.getFieldsValue();
      if (Object.keys(values).length > 0) {
        saveFormData(values);
      }
    };
  }, []);

  // 计算分页数据
  const paginatedData = () => {
    const { current, pageSize } = pagination;
    const start = (current - 1) * pageSize;
    const end = start + pageSize;
    return printRecordList.slice(start, end);
  };

  const openSelectMaterial = (id: React.Key) => {
    setSelectMaterialVisiable(true);
  };

  // 物料选择回调
  const handleSelectMaterial = (material: any) => {
    setSelectMaterialVisiable(false);
    if (material) {
      const { id, materialCode, materialName, spec } = material;
      form.setFieldsValue({
        bizId: id,
        materialCode: materialCode,
        materialName: materialName,
        materialSpec: spec,
      });
    }
  };

  // 重置表单
  const resetForm = () => {
    form.resetFields();
    localStorage.removeItem("nameplatePrintFormData");
  };

  // 执行打印
  const executePrint = () => {
    form.validateFields().then((values) => {
      setLoading(true);

      const paramValue = {
        lotNo: values.lotNo,
        productDate: values.productDate,
        team: values.team,
      }

      const params = {
        ...values,
        params: paramValue
      }

      printTemplateService
        .print(params)
        .then((res) => {
          const { recordList, ...rest } = res;
          // 修改这里：将新数据与现有数据合并
          setPrintRecordList((prevList) => {
            const newList = [...prevList, ...recordList];
            // 更新分页信息中的总数
            setPagination((prev) => ({
              ...prev,
              total: newList.length,
            }));
            return newList;
          });
          const clientData = rest;

          const protocol = window.location.protocol;
          const hostname = window.location.hostname;
          const requestUrl = `${protocol}//${hostname}:8001`;

          clientData.template = `${requestUrl}${clientData.template}`;
          console.log("模板下载地址：", clientData.template);

          const ws = new WebSocket("ws://localhost:8086/ws");

          ws.onopen = () => {
            ws.send(JSON.stringify(clientData));
          };

          ws.onmessage = () => {
            ws.close();
            setLoading(false);
          };

          ws.onclose = () => {
            console.log("关闭WebSocket连接！");
            setLoading(false);
          };

          ws.onerror = (evt) => {
            console.log(evt);
            message.error("打印服务调用失败");
            setLoading(false);
          };
        })
        .catch((e) => {
          console.error("打印失败", e);
          setLoading(false);
        });
    });
  };

  // 表格列定义
  const columns = [
    {
      title: "物料编码",
      dataIndex: "materialCode",
      key: "materialCode",
    },
    {
      title: "物料名称",
      dataIndex: "materialName",
      key: "materialName",
    },
    {
      title: "型号规则",
      dataIndex: "materialSpec",
      key: "materialSpec",
      width: 200,
    },
    {
      title: "标签编码",
      dataIndex: "labelCode",
      key: "labelCode",
      width: 380,
    },
    {
      title: "打印时间",
      dataIndex: "printTime",
      key: "printTime",
      width: 200,
    },
    {
      title: "打印人",
      dataIndex: "printUserName",
      key: "printUserName",
    },
  ];

  

  // 表单验证规则
  const rules = {
    itemCode: [{ required: true, message: "请选择物料" }],
    ruleCodeId: [{ required: true, message: "请选择编码规则" }],
    printTemplateId: [{ required: true, message: "请选择打印模板" }],
    lotNo: [{ required: true, message: "请输入批次号" }],
    productDate: [{ required: true, message: "请输入生产日期" }],
    team: [{ required: true, message: "请输入班组" }],
    printQty: [{ required: true, message: "请输入打印数量" }],
  };

  return (
    <div className="app-container">
      <Spin spinning={loading} tip="正在打印...">
        <StyledForm>
          <Form
            form={form}
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            style={{ paddingTop: "15px", paddingRight: "50px" }}
          >
            {/* 第一行 */}
            <Row gutter={20}>
              <Col span={8}>
                <Form.Item name="bizId" label="物料ID" hidden>
                  <Input />
                </Form.Item>
                <Form.Item
                  label="物料编码"
                  name="materialCode"
                  rules={[{ required: true, message: "请选择物料编码" }]}
                >
                  <Input.Search
                    placeholder="请选择物料"
                    allowClear
                    enterButton={<ExportOutlined />}
                    onSearch={openSelectMaterial}
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item name="materialName" label="物料名称">
                  <Input disabled />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="型号规格" name="materialSpec">
                  <Input placeholder="型号规格" disabled />
                </Form.Item>
              </Col>
            </Row>

            {/* 第二行 */}
            <Row gutter={20}>
              <Col span={8}>
                <Form.Item
                  label="编码规则"
                  name="ruleCodeId"
                  rules={rules.ruleCodeId}
                >
                  <Select
                    options={codeRuleList.map((item) => ({
                      label: item.ruleName,
                      value: item.id,
                    }))}
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  label="打印模板"
                  name="templateId"
                  rules={rules.printTemplateId}
                >
                  <Select
                    options={templateList.map((item) => ({
                      label: item.name,
                      value: item.id,
                    }))}
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="批次号" name="lotNo" rules={rules.lotNo}>
                  <Input placeholder="请输入批次号" />
                </Form.Item>
              </Col>
            </Row>

            {/* 第三行 */}
            <Row gutter={20}>
              <Col span={8}>
                <Form.Item
                  label="生产日期"
                  name="productDate"
                  rules={rules.productDate}
                >
                  <Input placeholder="生产日期" />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="班组" name="team" rules={rules.team}>
                  <Input placeholder="班组" />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  label="打印数量"
                  name="printQty"
                  rules={rules.printQty}
                >
                  <InputNumber
                    placeholder="打印数量"
                    style={{ width: "100%" }}
                  />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={20}>
              <Col span={24} style={{ textAlign: "right" }}>
                <Button
                  type="primary"
                  icon={<PrinterOutlined />}
                  onClick={executePrint}
                  style={{ fontSize: "16px", padding: "10px 20px" }}
                >
                  打印
                </Button>
                <Button
                  icon={<ReloadOutlined />}
                  onClick={resetForm}
                  style={{
                    fontSize: "16px",
                    padding: "10px 20px",
                    marginLeft: "10px",
                  }}
                >
                  重置
                </Button>
              </Col>
            </Row>
          </Form>
        </StyledForm>
        <Tabs
          defaultActiveKey="1"
          items={[
            {
              key: "1",
              label: "打印记录",
              children: (
                <Table
                  rowSelection={{ type: "checkbox" }}
                  columns={columns}
                  dataSource={paginatedData()}
                  scroll={{ y: 230 }}
                  rowKey="id"
                  pagination={{
                    current: pagination.current,
                    pageSize: pagination.pageSize,
                    total: pagination.total,
                    onChange: (page, pageSize) => {
                      setPagination({
                        ...pagination,
                        current: page,
                        pageSize: pageSize || pagination.pageSize,
                      });
                    },
                  }}
                />
              ),
            },
          ]}
        ></Tabs>
      </Spin>

      {/* 物料选择器 */}
      <SingleMaterialSelector
        open={selectMaterialVisiable}
        onCancel={() => setSelectMaterialVisiable(false)}
        onOk={(item) => handleSelectMaterial(item)}
      />
    </div>
  );
};

export default LabelPrint;
